package com.rongshu.view.userInfo.activity;

import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rongshu.R;
import com.rongshu.utils.Common;
import com.rongshu.utils.Constant;
import com.rongshu.utils.ControlScrollLayoutManager;
import com.rongshu.utils.LoginUtils;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.base.mvp.INetBean;
import com.rongshu.view.discovery.activity.UserHomePageActivity;
import com.rongshu.view.discovery.bean.AuthorDetailBean;
import com.rongshu.view.home.adapter.CommentAdapter;
import com.rongshu.view.home.entity.CommentDetails;
import com.rongshu.view.home.entity.CommentReplysBean;
import com.rongshu.view.home.entity.ContentClass;
import com.rongshu.view.home.fragment.dialog.InputNoteDialog;
import com.rongshu.view.home.listener.OnItemFunctionClickListener;
import com.rongshu.view.userInfo.iview.ReplyCommentView;
import com.rongshu.view.userInfo.presenter.ReplyCommentPresenter;
import com.rongshu.widget.BanyanDialog;
import com.widget.dialog.BottomListDialog;
import com.widget.titlebar.ImmersionBar;
import com.widget.toast.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.ResponseBody;

import static com.rongshu.utils.UserInfoUtils.getUserId;

public class ReplyCommentActivity extends BaseActivity<ReplyCommentPresenter> implements ReplyCommentView, OnItemFunctionClickListener {
    @BindView(R.id.txt_top_title)
    TextView txt_top_title;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;

    //map
    private Map<String, Object> map = null;
    //adapter
    private CommentAdapter mCommentAdapter = null;
    //评论的数据集合
    private List<CommentDetails.ResponseBean> mCommentDetails = null;
    //文章id
    private int contribute_id = 0;
    //评论的用户id
    private int userId = 0;
    //评论
    private int comment_id = 0, reply_id = 0;
    //local_position 局部刷新position
    private int local_position;
    private int reply_pageIndex = 1;
    private int reply_pageSize = 100;
    //评论点赞position
    private int likePosition = 0;
    //是否删除为回复
    private boolean isDeteleReply = false;
    //删除评论回复的position
    private int replyPosition = 0;
    //复制，回复，删除dialog
    private List<String> functions = null;
    //intent
    private Intent intent = null;
    //dialog
    private InputNoteDialog inputNoteDialog = null;
    //内容
    private String mContent = "";
    //提示
    private String mReplyContent = null;
    //@的用戶信息
    private LinkedHashMap<String, AuthorDetailBean> authorDetailBeanMap = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImmersionBar.with(this).keyboardEnable(false,
                WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING)
                .init();
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_reply_comment_view;
    }

    @Override
    protected void initView() {
        setPresenter(new ReplyCommentPresenter(this), this);
        txt_top_title.setText("留言");
        userId = getIntent().getIntExtra(Constant.INTENT_DATA, userId);
        contribute_id = getIntent().getIntExtra(Constant.INTENT_MESSAGE, contribute_id);
        comment_id = getIntent().getIntExtra(Constant.INTENT_FUNCTIONS, comment_id);
        //评论
        mCommentDetails = new ArrayList<>();
        mCommentAdapter = new CommentAdapter(this);
        mCommentAdapter.setResponseBeanList(mCommentDetails);
        mCommentAdapter.setOnItemFunctionClickListener(this);
        mCommentAdapter.setHasStableIds(true);
        //recyclerView
        ControlScrollLayoutManager manager = new ControlScrollLayoutManager(this);
        recyclerview.setLayoutManager(manager);
        recyclerview.setAdapter(mCommentAdapter);
        recyclerview.setFocusable(false);
        recyclerview.setFocusableInTouchMode(false);
        recyclerview.setNestedScrollingEnabled(false);
        //list
        authorDetailBeanMap = new LinkedHashMap<>();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void updateViews(boolean isRefresh) {
        getCommentMsg();
    }

    /**
     * 获取文章详情下的评论
     */
    private void getCommentMsg() {
        map = new HashMap<>();
        map.put("user_id", getUserId());
        map.put("comment_id", comment_id);
        presenter.getOnecomment((int) map.get("user_id"),
                (int) map.get("comment_id"),
                Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 评论点赞（任何评论）
     */
    private void getCommentlike(int comment_id) {
        map = new HashMap<>();
        map.put("user_id", getUserId());
        map.put("type", 1);//1文章，2帖子
        map.put("obj_id", contribute_id);//文章ID或者帖子ID
        map.put("comment_id", comment_id);
        presenter.getCommentlike(
                (int) map.get("user_id"),
                (int) map.get("type"),
                (int) map.get("obj_id"),
                (int) map.get("comment_id"),
                Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 文章评论删除/回复删除
     */
    public void getCommentOrReplyDelete(int comment_id, int reply_id) {
        map = new HashMap<>();
        map.put("user_id", getUserId());
        map.put("contribute_id", contribute_id);
        map.put("comment_id", comment_id);
        map.put("reply_id", reply_id);
        presenter.getCommentOrReplyDelete(
                (int) map.get("user_id"),
                (int) map.get("contribute_id"),
                (int) map.get("comment_id"),
                (int) map.get("reply_id"),
                Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 文章评论/评论回复/回复回复
     */
    private void postCommentOrReplyAdd(int comment_id, int reply_id, String content) {
        map = new HashMap<>();
        map.put("user_id", getUserId());
        map.put("contribute_id", contribute_id);
        map.put("comment_id", comment_id);
        map.put("reply_id", reply_id);
        ContentClass contentClass = new ContentClass();
        contentClass.setContents(content);
        contentClass.setTitle(null);
        StringBuilder aiteStrsb = new StringBuilder();
        for (Map.Entry<String, AuthorDetailBean> entry : authorDetailBeanMap.entrySet()) {
            if (!TextUtils.isEmpty(aiteStrsb)) {
                aiteStrsb.append(",");
            }
            aiteStrsb.append(entry.getValue().getUser_id_to());
        }
        contentClass.setAiteStr(aiteStrsb.toString());
        contentClass.setPenpalwill_id(null);
        presenter.postCommentOrReplyAdd((int) map.get("user_id"),
                (int) map.get("contribute_id"),
                (int) map.get("comment_id"),
                (int) map.get("reply_id"),
                Common.encryptionSign(map),
                contentClass);
        map.clear();
    }

    /**
     * 获取单个评论下的所有回复
     */
    private void getOnecommentDetail(int comment_id) {
        int user_id = getUserId();
        map = new HashMap<>();
        map.put("user_id", getUserId());
        map.put("comment_id", comment_id);
        map.put("pageIndex", reply_pageIndex);
        map.put("pageSize", reply_pageSize);
        presenter.getOnecommentDetail(user_id, comment_id, reply_pageIndex, reply_pageSize,
                Common.encryptionSign(map));
        map.clear();
    }

    @OnClick({R.id.layout_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_back:
                onBackPressed();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    /**
     * 复制，回复，删除评论dialog
     */
    private void showCopyReplyDeleteDialog(final String contents, final String bi_name, final int c_id, final int r_id, int from_uid) {
        if (mCommentAdapter == null) {
            return;
        }
        //复制，回复，删除
        functions = new ArrayList<>();
        functions.add("复制");
        functions.add("回复");
        //当前登录id
        int user_id = UserInfoUtils.getUserId();
        //当前文章的用户id
        int article_user_id = userId;
        //如果(1.登录id==文章的用户id,则是自己的文章，可以删除)(2.如果来自from_uid==登录id，可以删除)
        if (user_id == article_user_id || user_id == from_uid) {
            functions.add("删除");
        }
        BottomListDialog.Builder builder = new BottomListDialog.Builder(this);
        builder.setFunctions(functions)
                .setCancle(getString(R.string.cancle))
                .setCancle_color(R.color.color_2c2c2c)
                .setOption_color(R.color.color_2c2c2c)
                .setOnItemClickListener(new BottomListDialog.Builder.OnItemClickListener() {
                    @Override
                    public void onItemClick(int position, Dialog dialog) {
                        dialog.dismiss();
                        String funtion = functions.get(position);
                        if (funtion.equals("复制")) {
                            ClipboardManager mCM = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                            mCM.setPrimaryClip(ClipData.newPlainText(null, contents));
                            toast("复制成功");
                        } else if (funtion.equals("回复")) {
                            mReplyContent = "回复：" + bi_name;
                            comment_id = c_id;
                            reply_id = r_id;
                            getInputDialog().show(getSupportFragmentManager(), InputNoteDialog.class.getSimpleName());
                        } else if (funtion.equals("删除")) {
                            comment_id = c_id;
                            reply_id = r_id;
                            deleteCommentDeleteDialog();
                        }
                    }
                }).create().show();
    }

    /**
     * 删除该条评论提示
     */
    private void deleteCommentDeleteDialog() {
        BanyanDialog.Builder builder = new BanyanDialog.Builder(this);
        builder.setTitle("确认要删除该条评论吗？")
                .setLeft("取消")
                .setRight("确定");
        final BanyanDialog dialog = builder.create();
        builder.setDialogOnClick(new BanyanDialog.Builder.onClickListener() {
            @Override
            public void leftClickListener() {
                dialog.dismiss();
            }

            @Override
            public void rightClickListener() {
                dialog.dismiss();
                getCommentOrReplyDelete(comment_id, reply_id);
            }
        });
        dialog.show();
    }

    /**
     * 显示输入框弹窗
     */
    private InputNoteDialog getInputDialog() {
        inputNoteDialog = InputNoteDialog.getInstance(mContent, mReplyContent, authorDetailBeanMap);
        inputNoteDialog
                .setOnDialogInputListener(new InputNoteDialog.OnDialogInputListener() {
                    @Override
                    public void sendCommentSuccess(LinkedHashMap<String, AuthorDetailBean> map, String content) {
                        authorDetailBeanMap = map;
                        content = Uri.encode(content, "utf-8");
                        postCommentOrReplyAdd(comment_id, reply_id, content);
                    }

                    @Override
                    public void dimiss(LinkedHashMap<String, AuthorDetailBean> map, String content, String replyContent) {
                        inputNoteDialog.dismissDialog();
                        inputNoteDialog = null;
                        authorDetailBeanMap = map;
                        mContent = content;
                        mReplyContent = replyContent;
                    }
                });
        return inputNoteDialog;
    }

    /**
     * 清空标识
     */
    private void cleanIdentifying() {
        reply_id = 0;
        if (authorDetailBeanMap != null) {
            authorDetailBeanMap.clear();
        }
    }

    @Override
    public void onItemClickListener(int position, String contents, String bi_name, int comment_id, int from_uid) {
        this.local_position = position;
        this.isDeteleReply = false;
        showCopyReplyDeleteDialog(contents, bi_name, comment_id, 0, from_uid);
    }

    @Override
    public void onItemChildClickListener(int position, int replyPosition, String contents, String bi_name, int comment_id, int reply_id, int reply_user_id) {
        this.local_position = position;
        this.replyPosition = replyPosition;
        this.isDeteleReply = true;
        showCopyReplyDeleteDialog(contents, bi_name, comment_id, reply_id, reply_user_id);
    }

    @Override
    public void onItemExpandClickListener(boolean isExpanded, int pageSize, int comment_id, int local_position) {
        if (isExpanded) {
            this.isDeteleReply = false;
            this.local_position = local_position;
            getOnecommentDetail(comment_id);
        }
    }

    @Override
    public void onItemHeaderClickListener(int userid, boolean is_allow_browse_homepage) {
        //user_id
        int user_id = getUserId();
        if (user_id == 0) {
            LoginUtils.toLogin(this);
            return;
        }
        if (user_id == userid) {
            intent = new Intent(this, PersonDetailsActivity.class);
        } else {
            intent = new Intent(this, UserHomePageActivity.class);
            intent.putExtra(Constant.USER_ID, userid);
        }
        startActivity(intent);
    }

    @Override
    public void onItemGiveLikeClickListener(int comment_id, int position) {
        this.likePosition = position;
        getCommentlike(comment_id);
    }

    @Override
    public void onCommentMsg(List<CommentDetails.ResponseBean> responseBeanList) {
        mCommentDetails.addAll(responseBeanList);
        mCommentAdapter.notifyDataSetChanged();
    }

    @Override
    public void onPostCommentOrReplyAdd(ResponseBody body) {
        try {
            String json = body.string().toString();
            JSONObject object = new JSONObject(json);
            int errCode = object.getInt("ErrCode");
            String respose = object.getString("Response");
            if (errCode == 0) {
                List<CommentReplysBean> replysBeans = new Gson().fromJson(respose, new TypeToken<List<CommentReplysBean>>() {
                }.getType());
                if (replysBeans != null && !replysBeans.isEmpty()) {
                    //原先的评论回复
                    if (mCommentDetails != null && !mCommentDetails.isEmpty()) {
                        List<CommentReplysBean> list = new ArrayList<>();
                        CommentDetails.ResponseBean bean = mCommentDetails.get(local_position);
                        List<CommentReplysBean> replys = bean.getComment_replys();
                        //重新填充一个集合
                        list.addAll(replys);
                        replys.clear();
                        replys.add(replysBeans.get(0));
                        if (!list.isEmpty()) {
                            //添加以前的数据
                            replys.addAll(list);
                        }
                        //此时，comment_replyCount数量需要增加1
                        int count = bean.getComment_replyCount();
                        count = count + 1;
                        bean.setComment_replyCount(count);
                        mCommentAdapter.notifyItemRangeChanged(local_position, mCommentAdapter.getItemCount() - local_position);
                    }
                }
                toast("回复成功");
                if (inputNoteDialog != null) {
                    inputNoteDialog.dismissDialog();
                }
                //清空标识
                cleanIdentifying();
            } else {
                toast("回复失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onOnecommentDetail(List<CommentReplysBean> commentReplysBeans) {
        if (mCommentAdapter == null) {
            return;
        }
        mCommentAdapter.getResponseBeanList().get(local_position).setComment_replys(commentReplysBeans);
        mCommentAdapter.notifyItemRangeChanged(local_position, mCommentAdapter.getItemCount() - local_position);
    }

    @Override
    public void onCommentlike(INetBean iNetBean) {
        if (iNetBean.getErrCode() == 0) {
            if (iNetBean.getErrMsg().equals("留言点赞成功")) {
                if (mCommentAdapter != null) {
                    List<CommentDetails.ResponseBean> responseBeanList = mCommentAdapter.getResponseBeanList();
                    if (responseBeanList != null) {
                        int likeCount = responseBeanList.get(likePosition).getLikeCount();
                        responseBeanList.get(likePosition).setLikeCount(likeCount + 1);
                        responseBeanList.get(likePosition).setIslike(1);
                        mCommentAdapter.notifyItemRangeChanged(likePosition, 1, mCommentAdapter.GIVELIKE);
                    }
                }
            }
        } else {
            ToastUtils.show(iNetBean.getErrMsg());
        }
    }

    @Override
    public void onCommentOrReplyDelete(INetBean bean) {
        if (bean.getErrCode() == 0) {
            if (mCommentAdapter == null) {
                return;
            }
            List<CommentDetails.ResponseBean> responseBeans = mCommentAdapter.getResponseBeanList();
            if (isDeteleReply) {//回复评论
                CommentDetails.ResponseBean response = responseBeans.get(local_position);
                List<CommentReplysBean> replysBeans = response.getComment_replys();
                replysBeans.remove(replyPosition);
                int comment_replyCount = response.getComment_replyCount();
                if (comment_replyCount > 0) {
                    comment_replyCount = comment_replyCount - 1;
                    response.setComment_replyCount(comment_replyCount);
                }
                //如果此时集合中数据和comment_replyCount数据不一致，说明二者数据不一致，需要重新请求
                int replyCount = replysBeans.size();
                if (replyCount < comment_replyCount) {
                    mCommentAdapter.notifyItemRangeChanged(local_position, mCommentAdapter.getItemCount() - local_position);
                    getOnecommentDetail(comment_id);//(此处问题在于，如果获取不到数据，当前一条没有更新view)
                } else {
                    mCommentAdapter.notifyItemRangeChanged(local_position, mCommentAdapter.getItemCount() - local_position);
                }
            } else {
                responseBeans.remove(local_position);
                mCommentAdapter.notifyItemRemoved(local_position);
                mCommentAdapter.notifyItemRangeChanged(local_position, mCommentAdapter.getItemCount() - local_position);
            }
            toast("删除成功");
        } else {
            toast("删除失败");
        }
        //清空标识
        cleanIdentifying();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (inputNoteDialog != null) {
            inputNoteDialog.dismiss();
            inputNoteDialog = null;
        }
    }
}
